const FILE_URL = process.env.VUE_APP_BASE_URL

export const imageSuffixes = ['.jpg', '.png', '.gif', '.jpeg']
export const videoSuffixes = ['.avi', '.mp4', '.mpeg', '.wmv', '.mov']
export const audioSuffixes = ['.mp3', '.wma', '.avi', '.mdi', '.rmvb', '.ogg']
export const pdfSuffixes = ['.pdf']
export const pptSuffixes = ['.ppt', '.pptx']
export const excelSuffixes = ['.excel', '.xlsx']
export const wordSuffixes = ['.word', '.docx']
export const zipSuffixes = ['.zip']
export const FILETYPE = {
  IMAGE: 'IMAGE',
  VIDEO: 'VIDEO',
  AUDIO: 'AUDIO',
  EXCEL: 'EXCEL',
  PDF: 'PDF',
  PPT: 'PPT',
  WORD: 'WORD',
  ZIP: 'ZIP',
  OTHER: 'OTHER'
}

export function isImageByUrl (src) {
  return getFileTypeByUrl(src) === FILETYPE.IMAGE
}

export function isVideoByUrl (src) {
  return getFileTypeByUrl(src) === FILETYPE.VIDEO
}

export function isAduioByUrl (src) {
  return getFileTypeByUrl(src) === FILETYPE.AUDIO
}
export function isExcelByUrl (src) {
  return getFileTypeByUrl(src) === FILETYPE.EXCEL
}
export function isPdfByUrl (src) {
  return getFileTypeByUrl(src) === FILETYPE.PDF
}
export function isPptByUrl (src) {
  return getFileTypeByUrl(src) === FILETYPE.PPT
}
export function isWordByUrl (src) {
  return getFileTypeByUrl(src) === FILETYPE.WORD
}
export function isZipByUrl (src) {
  return getFileTypeByUrl(src) === FILETYPE.ZIP
}

export function getFullUrl (src) {
  const rx = /^https?:\/\//i
  return rx.test(src) ? src : FILE_URL + src
}

export function getFileTypeByUrl (src) {
  src = src.toLowerCase()
  const reg = /\.[^.]+$/
  const matches = reg.exec(src)
  if (matches) {
    const suffix = matches[0]
    if (imageSuffixes.includes(suffix)) return FILETYPE.IMAGE
    if (videoSuffixes.includes(suffix)) return FILETYPE.VIDEO
    if (audioSuffixes.includes(suffix)) return FILETYPE.AUDIO
    if (excelSuffixes.includes(suffix)) return FILETYPE.EXCEL
    if (pdfSuffixes.includes(suffix)) return FILETYPE.PDF
    if (pptSuffixes.includes(suffix)) return FILETYPE.PPT
    if (wordSuffixes.includes(suffix)) return FILETYPE.WORD
    if (zipSuffixes.includes(suffix)) return FILETYPE.ZIP
  }
  return FILETYPE.OTHER
}
export function download (url, fileName) {
  const xhr = new XMLHttpRequest()
  xhr.open('get', url)
  xhr.responseType = 'blob'
  xhr.send()
  xhr.onload = function (sues) {
    const data = xhr.response
    const imgurl = URL.createObjectURL(data)
    let a = document.createElement('a')
    a.href = imgurl
    a.download = fileName || ''
    a.click()
    a = null
  }
}
